import React, { useMemo, useState, useEffect, SetStateAction, Key } from 'react';
import { message, Button, Table, Form } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { uuid } from '@inbiz/utils';
import { EditableRow, EditableCell } from './EditCell';
import { getExpressionArray } from '../../utils';
import { getVariateList } from '../../server';
import './style.less';

interface DataType {
    id: SetStateAction<string>;
    key: string;
    name: string;
    age: number;
    address: string;
    tags: string[];
}

const ConditionEditableContext = React.createContext<any>(null);
export { ConditionEditableContext };

export default function Expression(props: any) {
    const { value, onChange, processId } = props;
    const [data, setData] = useState<any[]>([])
    const [variateList, setVariateList] = useState<any[]>([]);
    const [conditionSettingsSelectedRowKeys, setConditionSettingsSelectedRowKeys] = useState<Key[]>([]);
    const [curId, setCurId] = useState<string>('')
    const [loading, setLoading] = useState<boolean>(false);
    const [form] = Form.useForm();

    const defaultColumns: any = useMemo(() => {
        return [
            {
                title: '左括号',
                dataIndex: 'leftBracket',
                editable: true,
            },
            {
                title: '名称',
                dataIndex: 'varName',
                ellipsis: true,
                editable: true,
            },
            {
                title: '逻辑符',
                dataIndex: 'symbolicLogic',
                editable: true,
            },
            {
                title: '比较值',
                dataIndex: 'compareValue',
                editable: true,
            },
            {
                title: '右括号',
                dataIndex: 'rightBracket',
                editable: true,
            },
            {
                title: '逻辑',
                dataIndex: 'logic',
                editable: true,
            },
        ]
    }, []);

    useEffect(() => {
        let _value = [];
        try {
            _value = value ? typeof value === 'string' ? getExpressionArray(JSON.parse(value)) : getExpressionArray(value) : [];
        } catch (error) {
            console.log(error);
        }
        setData(_value);
    }, [value]);

    const columns: ColumnsType<DataType> = useMemo(() => {
        return defaultColumns.map((col: { editable: any; dataIndex: any; title: any; required: any; }) => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: (record: any) => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    required: col.required,
                    variateId: curId,
                    setNowKey: (e: any) => setCurId(e),
                    handleSave,
                    variateList,
                }),
            };
        })
    }, [curId, defaultColumns, variateList]);

    const handleSave = (row: any) => {
        const newData: any = [...data];
        const index = newData.findIndex((item: { id: string }) => row.id === item.id);
        const item: any = newData[index];
        newData.splice(index, 1, {
            ...item,
            ...row,
        });
        setData(newData);
        onChange(newData);
    };

    const addConditionRow = () => {
        let _data = data.concat({
            id: 'condition' + uuid(20, 60),
            leftBracket: '',
            varName: '',
            symbolicLogic: '',
            compareValue: '',
            rightBracket: '',
            logic: '',
        });
        setData(_data);
        onChange(_data);
    };

    const delCondition = () => {
        if (conditionSettingsSelectedRowKeys.length === 0) {
            message.error('请选中要删除的条件');
        } else {
            let _data = data.filter((item: any) => !conditionSettingsSelectedRowKeys.includes(item.id))
            setData(_data);
            onChange(_data);
            setConditionSettingsSelectedRowKeys([]);
        }
    };

    const onSelectChange = (newSelectedRowKeys: Key[]) => {
        setConditionSettingsSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        selectedRowKeys: conditionSettingsSelectedRowKeys,
        onChange: onSelectChange,
    };

    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };

    useEffect(() => {
        setLoading(true);
        getVariateList({ processId }).then((res) => {
            if (res?.code == '200') {
                if (res?.details?.rows) {
                    setVariateList(res?.details?.rows);
                }
            } else {
                message.error(res?.message);
            }
            setLoading(false);
        }).catch((error) => {
            message.error(error);
            setLoading(false);
        })
    }, []);

    return (
        <div className='process-designer-expression'>
            <>
                <div className='process-designer-expression-buttons'>
                    <Button type='primary' onClick={addConditionRow}>添加</Button>
                    <Button danger onClick={delCondition}>删除</Button>
                </div>
                <div className='process-designer-expression-table'>
                    <Form form={form}>
                        <ConditionEditableContext.Provider value={form}>
                            <Table
                                columns={columns}
                                components={components}
                                dataSource={data}
                                rowSelection={rowSelection}
                                pagination={false}
                                size="small"
                                rowKey="id"
                                bordered
                                loading={loading}
                                rowClassName={'process-designer-condition-setting-modal-table-row'}
                            />
                        </ConditionEditableContext.Provider>
                    </Form>
                </div>
            </>
        </div>
    );
};